/**
 * Depends:
 * utility.json.loader.js
 * utility.json.render.js
 */
$.fn.searchParamsWidget = function(options){
	var $this = this;
	options = options || {};
	
	var searchStringSelector 	= options.searchStringSelector 		|| '#q';
	var markSelector 		= options.markSelector 			|| '#mark';
	
	var markCollectionSelector  = options.markCollectionSelector  || '[class^="mark-set-"] [id^="markmodel-"]';
	var modelCollectionSelector = options.modelCollectionSelector || '[class^="model-set-"] [id^="markmodel-"]';
	
	var stateCollectionSelector  = options.stateCollectionSelector  || '[class^="state-set-"] [id^="statecity-"]';
	var cityCollectionSelector   = options.cityCollectionSelector   || '[class^="city-set-"] [id^="statecity-"]';
	/**
	 *  
	 */
	$this._init = function(){
		$this.markCollection  = $(this).find(markCollectionSelector);
		$this.modelCollection = $(this).find(modelCollectionSelector);
		$this.stateCollection  = $(this).find(stateCollectionSelector);
		$this.cityCollection = $(this).find(cityCollectionSelector);
	};
	/**
	 * 
	 */
	$this._bindEvents= function(){
		$this.markCollection.change(function(){
			$this.loadModels($(this).attr('name'));
			$this.modelCollection.change();
		});
		
		$this.stateCollection.change(function(){
			$this.loadCities($(this).attr('name'));
			$this.cityCollection.change();
		});
	};
	
	/**
	 * @todo Make subcategory loading
	 */
	$this.loadModels = function(pairNumber){
		var pairNumber = pairNumber || 0;
		pairNumber = utility.removeText(pairNumber);
		var items = utility.json.render({
			data : utility.json.loader({
				url : 'ajax/get-models',
				data : {identifier : $this.markCollection.filter('#markmodel-'+pairNumber+'-mark').val()}
			})
		});
		$this.modelCollection.filter('#markmodel-'+pairNumber+'-model').empty().append(items);
	};
	
	/**
	 * 
	 */
	$this.loadCities = function(pairNumber){
		var pairNumber = pairNumber || 0;
		pairNumber = utility.removeText(pairNumber);
		var items = utility.json.render({
			data : utility.json.loader({
				url : 'ajax/get-cities',
				data : {identifier : $this.stateCollection.filter('#statecity-'+pairNumber+'-state').val()}
			})
		});
		$this.cityCollection.filter('#statecity-'+pairNumber+'-city').empty().append(items);
	};
	
	/**
	 * Implementation
	 */
	$this._init();
	$this._bindEvents();
	
	return $(this);
};